package com.example.springbootdemo.bean.core;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.springbootdemo.bean.kernelApi.LoginData;
import com.example.springbootdemo.bean.kernelApi.Result;
import com.microsoft.signalr.HubConnection;
import com.microsoft.signalr.HubConnectionBuilder;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class HubConnectionManager {

    @Getter
    private HubConnection hubConnection;

    private boolean tokenIsValid = false;
    public static Date expiresTime = new Date();
     String token;

    @PostConstruct
    public void initializeHubConnection() {
        hubConnection = HubConnectionBuilder.create("https://orginone.cn/orginone/kernel/hub")
                .build();
        hubConnection.setKeepAliveInterval(3000);
        hubConnection.on("ReceiveMessage", (message) -> {
            System.out.println("Received message: " + message);
        }, String.class);
        hubConnection.onClosed((err) -> {
            try {
                Thread.sleep(8000);
            } catch (InterruptedException e) {
                log.error("hub--InterruptedException while sleeping: " + e.getMessage());
                initializeHubConnection();
            }
            hubConnection.start().blockingAwait();
//            System.out.println(verifyTokenAndUpdateConnection());
       /*     if (verifyTokenAndUpdateConnection()) {
                log.error("重新生成token");
                login();
            }*/
        });
        hubConnection.start().blockingAwait();
        login();

    }

    public String getHubConnectionToken() {
        return token;
    }

    public Boolean  verifyTokenAndUpdateConnection() {
        if (StringUtils.isBlank(token)) {
            return true;
        }else {
            var type = new Result<LoginData>();
            var result = hubConnection.invoke(type.getClass(), "TokenAuth", token).blockingGet();

            System.out.println("----------");
            System.out.println(result);
//            Result(code=200, data=, msg=success, success=true)
            return false;
        }

    }
    private <T> Result<T> getJsonData(Object obj, Class<T> clazz){
        var json = JSON.toJSONString(obj);
        var result = JSON.parseObject(json, new TypeReference<Result<T>>(clazz){});
        return result;
    }



    private void login() {
        log.warn("刷新token");
        Map<String, String> req = new HashMap<>(2);
        req.put("account", "18767399041");
        req.put("pwd", "Ayu*1996");
        var type = new Result<LoginData>();
        var result = hubConnection.invoke(type.getClass(), "Login", req).blockingGet();
        if (result.getCode()== HttpStatus.OK.value()){
            tokenIsValid = true;
            var obj = getJsonData(result,LoginData.class);
            token = obj.getData().getAccessToken();
            expiresTime = new Date(System.currentTimeMillis() + obj.getData().getExpiresIn() * 1000L);
        }else {
             log.error("请求登录失败");
        }
    }

    @Scheduled(fixedRate = 60 * 1000)
    public void updateToken() {
        log.warn("执行了刷新token任务");
        var now = new Date();
        var diffTime = expiresTime.getTime() - now.getTime();
        if (diffTime < 5 * 60 * 1000) {
            log.info("get new token");
            login();
        }
    }
}
